import React,{Component} from 'react';
import SomethingTodo from './SomethingTodo'
import { isTemplateElement } from '@babel/types';

export default class OptionTodo extends Component{
    constructor(props){
        super(props);
        this.state={
            todoList:[
                {id:1,name:"Todo One",isCompleted:false},
                {id:2,name:"Todo Two",isCompleted:false},
                {id:3,name:"Todo Three",isCompleted:false}
            ],
            inputVal:''
        }
    }

    //获取文本框的输入值
    handleInputChange(e){
        //console.log(e.target.value);
        this.setState({
            inputVal:e.target.value
        })
    }
    
    //处理增加按钮
    handleAddClick(){
        for(var i=0;i<this.state.todoList.length;i++){}
       //获取到最后的id值，构造对象
        let id=i+1;
        let value=this.state.inputVal;
        let obj={id:id,name:value,isCompleted:false};
        this.setState({
            todoList:[...this.state.todoList,obj],
            inputVal:''
        })
        {console.log(this.state.todoList);}
    }

    //删除功能
    deleteStudentHandler=index=>{
        const {todoList}=this.state;
        todoList.splice(index,1);
        this.setState({
            todoList:todoList
       })
    }

    //状态改变
    statusChangeHandler(id){
        const {todoList}=this.state;
        const todoIndex=todoList.findIndex(item=>{
            return item.id===id;});
        //console.log(todoIndex);
        let todo=todoList[todoIndex];
        //console.log(todo.isCompleted);
        todo.isCompleted=!todo.isCompleted;
        //console.log(todo.isCompleted);
        todoList[todoIndex]=todo;
        this.setState({
            todoList:todoList
          })
    }
   

    render(){
        const inputStyle={
            width:'25%',
            height:'25px',
        }
        const btnStyle={
            marginLeft:'5px',
            width:'100px',
            height:'30px',
            fontSize:'15px',
            backgroundColor:'lightblue',
            border:'0'
        }
        return (<div>
            <input style={inputStyle} 
            value={this.state.inputVal} 
            onChange={this.handleInputChange.bind(this)}></input>
            <button style={btnStyle} onClick={this.handleAddClick.bind(this)}>Add Todo</button>
            
            <ul>
                {
                     this.state.todoList.map((item,index)=>{
                        return <SomethingTodo key={index} name={item.name} isCompleted={item.isCompleted} 
                        statusChangeHandler={()=>this.statusChangeHandler(item.id)} deleteStudentHandler={()=>this.deleteStudentHandler(index)}></SomethingTodo>
                    })
                }
            </ul>

        </div>)

    }
}